﻿using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Input;
using Noria.Core;
using Noria.Scenarios.BankPay.Properties;

namespace Noria.Scenarios.BankPay
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            editCredit.Text = Settings.Default.CreditCardNo;
            editMonth.Text = Settings.Default.CreditCardMonth;
            editYear.Text = Settings.Default.CreditCardYear;
            editCVV2.Text = Settings.Default.CreditCardCVV2;
            editPwd.Password = Settings.Default.CreditCardPwd;
        }

        private void BtnInvoke_Click(object sender, RoutedEventArgs e)
        {
            base.Cursor = Cursors.Wait;

            try
            {
                TDocument doc = TDocument.FromTitle(((char)0xA0).ToString());
                AutomationElement[] secureCtrls = doc.GetActiveXElements(null);

                // sort ActiveX controls
                secureCtrls = secureCtrls.OrderBy(p => p.Current.BoundingRectangle.Y).
                    ThenBy(p => p.Current.BoundingRectangle.X).ToArray();

                AutomationElement axCardPayNo = secureCtrls[0];
                AutomationElement axCardPayPwd = secureCtrls[1];
                AutomationElement axCreditCardMonth = secureCtrls[2];
                AutomationElement axCreditCardYear = secureCtrls[3];
                AutomationElement axCreditCardCVV2 = secureCtrls[4];

                ActiveX.SetText(axCardPayNo, editCredit.Text);
                ActiveX.SetText(axCardPayPwd, editPwd.Password);
                ActiveX.SetText(axCreditCardMonth, editMonth.Text);
                ActiveX.SetText(axCreditCardYear, editYear.Text);
                ActiveX.SetText(axCreditCardCVV2, editCVV2.Text);
            }
            catch (Exception x)
            {
                MessageBox.Show("未知错误: {0}" + x);
            }

            base.Cursor = Cursors.Arrow;
        }

        private void BtnExit_Click(object sender, RoutedEventArgs e)
        {
            base.Close();
        }
    }
}
